<?php
namespace Wechat\Controller;

class ApiController extends \Think\Controller{
    private $customer_id;
    public $post_data; //微信服务器发送过来的数据
    public $rule;
    public $replyobj;
    public $resultStr;
    
    public function index(){
        $this->customer_id = intval($_REQUEST['id']);
        $customerRow = D('Customer')->find($this->customer_id);
        if(isset($_GET['echostr']) && isset($_GET["signature"]) && isset($_GET["timestamp"]) && isset($_GET["nonce"])){
            echo $this->valid($customerRow['username']); //公众平台校验
        }else{
            echo $this->responseMsg();
        }
    }

    //解析微信post过来的数据
    private function getPostData(){
        $postObj = simplexml_load_string($GLOBALS["HTTP_RAW_POST_DATA"], 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = array();
        //通用消息
        $data['FromUserName'] = trim($postObj->FromUserName);
        $data['ToUserName'] = trim($postObj->ToUserName);
        $data['FromMsgType'] = trim($postObj->MsgType);
        $data['Keyword'] = trim($postObj->Content);
        $data['CreateTime'] = trim($postObj->CreateTime);
        //图片消息
        $data['PicUrl'] = trim($postObj->PicUrl);
        //语音消息
        $data['Recognition']  = trim($postObj->Recognition);
        //地理位置消息
        $data['Location_X'] = trim($postObj->Location_X);
        $data['Location_Y'] = trim($postObj->Location_Y);
        $data['Label'] = trim($postObj->Label);
        //事件推送
        $data['Event'] = trim($postObj->Event);
        $data['EventKey'] = trim($postObj->EventKey);
        
        if($data['FromMsgType'] == 'image'){
            $data['Keyword'] = '[发送图片]';
        }elseif($data['FromMsgType'] == 'voice'){
            $data['Keyword'] = $data['Recognition'];
        }elseif($data['FromMsgType'] == 'location'){
            $data['Keyword'] = '[发送位置]'.$data['Label'];
        }elseif($data['Event'] == 'CLICK' || $data['Event'] == 'VIEW'){//菜单点击事件
            $data['Keyword'] = $data['EventKey'];
        }
        
        return $data;
    }
    
    //回复微信
    private function responseMsg(){
        $Member = M('WxMember');
        $this->post_data = $this->getPostData();//解析微信post过来的数据
        if (empty($this->post_data['FromUserName'])) return '';
		
        $this->addMessage();//收消息入库
        
        //添加或更新会员
        $memberRow = $Member->where(array("fromuser"=>$this->post_data['FromUserName'],"customer_id"=>$this->customer_id))->find();
        
        $rowMem = array();
        $rowMem['fromuser']    = $this->post_data['FromUserName'];
        $rowMem['timesign']    = $this->post_data['CreateTime'];
        $rowMem['customer_id'] = $this->customer_id;
        
        if(strtolower($this->post_data['Event']) == 'unsubscribe'){
            $rowMem['unsubscribe_time'] = time();
            $rowMem['status'] = '0';
        }else{
            if(strtolower($this->post_data['Event']) == 'subscribe'){
                $rowMem['subscribe_time'] = time();
                $rowMem['status'] = '1';
            }
            //非取消关注时获取用户头像昵称等信息
            if($this->post_data['FromUserName'] && empty($memberRow['nickname'])){

                //获取用户基本信息
                try {
                    $userService = new \Overtrue\Wechat\User(C('APPID'), C('APPSECRET'));
                    $userInfo = $userService->get($this->post_data['FromUserName']);
                } catch (\Exception $e) {
                    $userInfo = array();
                }

                if(!empty($userInfo['nickname'])){
                    $rowMem['group_id']   = $userInfo['groupid'];
                    $rowMem['nickname']   = $userInfo['nickname'];
                    $rowMem['headimgurl'] = $userInfo['headimgurl'];
                    $rowMem['sex']        = $userInfo['sex'];
                    $rowMem['language']   = $userInfo['language'];
                    $rowMem['country']    = $userInfo['country'];
                    $rowMem['province']   = $userInfo['province'];
                    $rowMem['city']       = $userInfo['city'];
                }
            }
        }
        empty($memberRow) ? $Member->add($rowMem) : $Member->where(array('id'=>$memberRow['id']))->save($rowMem);
        //关注+取消关注
        if(strtolower($this->post_data['Event'])=='subscribe' || strtolower($this->post_data['Event'])=='unsubscribe'){
            //插入关注记录
            $careStatus = strtolower($this->post_data['Event']) == 'subscribe' ? '1' : '0';
            M('WxCareRecord')->add(array('is_care'=>$careStatus,'fromuser'=>$this->post_data['FromUserName'],'customer_id'=>$this->customer_id));

            //关注自动回复
            $replyRow = M("WxAutoReply")->where(array('customer_id'=>$this->customer_id,'type'=>'1','state'=>'1'))->find();
            if($careStatus == '1' && $replyRow){
                if($replyRow['is_content'] == '1'){
                    return $this->create_xmlcontent('text', $replyRow['content']);
                }else{
                    $this->post_data['Keyword'] = $replyRow['keyword'];
                }
            }else{
                return false;
            }
        }
        if(strtolower($this->post_data['Event']) != 'location')
            $returnxml = $this->getInfo();//暂不处理自动上传地理位置的信息
        return $returnxml;
    }
    
    //获取回复内容
    public function getInfo(){
        $preUrl = U('Home/Pre/index', array('fromuser' => encodeOpenid($this->post_data['FromUserName'], $this->post_data['CreateTime'])), false, true);
        if($this->post_data['Keyword'] == '小红卡活动' || $this->post_data['Keyword'] == '晒照'){
            $text = "乐享生活，小红卡与您一路同行。\n感谢关注上海农商银行工会卡。\n参与【晒出最美旅行瞬间】活动请<a href='".$preUrl."'>点击这里</a>\n来帮你的好友助力点赞请<a href='".$preUrl."&to=lists'>点击这里</a>";
            \Think\Log::record($text, 'WARN');
            return $this->create_xmlcontent('text', $text);
        }elseif($this->post_data['Keyword'] == '我要晒照'){
            $text = "参与【晒出最美旅行瞬间】活动请<a href='".$preUrl."'>点击这里</a>";
            \Think\Log::record($text, 'WARN');
            return $this->create_xmlcontent('text', $text);
        }elseif($this->post_data['Keyword'] == '最美照片墙'){
            $text = "查看小伙伴们上传的旅行美照请<a href='".$preUrl."&to=lists'>点击这里</a>！输入好友照片编号来帮TA点赞助力吧！";
            \Think\Log::record($text, 'WARN');
            return $this->create_xmlcontent('text', $text);
        }else{
            $keywordinfo = M('WxKeyword')->where(array('customer_id'=>$this->customer_id,'keyword'=>$this->post_data['Keyword']))->find();
            if(empty($keywordinfo)){
                //无匹配回复
                if($replyRow = M("WxAutoReply")->where(array('customer_id'=>$this->customer_id,'type'=>'2','state'=>'1'))->find()){
                    return $this->create_xmlcontent('text', $replyRow['content']);
                }else{
                    return false;
                }
            }else{
                $data = array();
                if($keywordinfo['type'] == 'text'){
                    $data = $this->getText($keywordinfo['common_id']);
                }elseif($keywordinfo['type'] == 'single'){
                    $data = $this->getSingle($keywordinfo['common_id']);
                    return $data;
                }elseif($keywordinfo['type'] == 'pic'){
                    $data = $this->getPic($keywordinfo['common_id']);
                }
                return $this->create_xmlcontent($data['msgtype'], $data['content'], $data['title'], $data['description'], $data['picurl'], $data['url'], $data['bodystr']);
            }
        }
    }
    
    //收到的消息入库
    protected function addMessage() {
        $row                = array();
        $row['customer_id'] = $this->customer_id;
        $row['fromuser']    = $this->post_data['FromUserName'];
        $row['touser']      = $this->post_data['ToUserName'];
        $row['msgtype']     = $this->post_data['FromMsgType'];
        $row['msg_content'] = $this->post_data['Keyword'];
        $row['create_time'] = $this->post_data['CreateTime'];
        M('WxMessage')->add($row);
    }
    
    //文字回复
    public function getText($id){
        $WxCommon = M('WxCommon');
        $inforesult = $WxCommon->where(array('id'=>$id,'state'=>'1'))->find();
        $WxCommon->where(array('id'=>$id))->setInc('push_num');//推送量+1
        return array('msgtype'=>'text','content'=>$inforesult['content']);
    }
    
    //图文回复
    public function getSingle($id){
        $WxCommon   = M('WxCommon');
        $xmlItem    = '';
        $inforesult = array();
        $WxCommon->where(array('id'=>$id))->setInc('push_num');//推送量+1

        //获取所有图文
        $inforesult[] = $WxCommon->where(array('id'=>$id,'state'=>'1'))->find();
        if ($commonDetail = M('WxCommonDetail')->where(array('common_id'=>$id))->select()) {
            foreach ($commonDetail as $dv) {
                $inforesult[] = $dv;
            }
        }

        if (empty($inforesult)) return '';

        //组装xml中的文章内容
        $vars = array('fromuser'=>encodeOpenid($this->post_data['FromUserName'], $this->post_data['CreateTime']));
        foreach ($inforesult as $key => $value) {
            $xmlItem .= "<item>
                <Title><![CDATA[".htmlspecialchars_decode($value['title'])."]]></Title> 
                <Description><![CDATA[".htmlspecialchars_decode($value['content'])."]]></Description>
                <PicUrl><![CDATA[".C('IMG_PREFIX').$value['pic']."]]></PicUrl>
                <Url><![CDATA[".htmlspecialchars_decode($value['url'])."]]></Url>
                </item>";
        }

        $xmlcontent = "<xml>
            <ToUserName><![CDATA[".$this->post_data['FromUserName']."]]></ToUserName>
            <FromUserName><![CDATA[" . $this->post_data['ToUserName']."]]></FromUserName>
            <CreateTime>".time()."</CreateTime>
            <MsgType><![CDATA[news]]></MsgType>
            <ArticleCount>".count($inforesult)."</ArticleCount>
            <Articles>".$xmlItem."</Articles>
            </xml>";
        return $xmlcontent;
    }
    
    //文字回复
    public function getPic($id){
        $WxCommon = M('WxCommon');
        $inforesult = $WxCommon->where(array('id'=>$id,'state'=>'1'))->find();
        $WxCommon->where(array('id'=>$id))->setInc('push_num');//推送量+1
        return array('msgtype'=>'image','content'=>$inforesult['media_id']);
    }
    
    /**
     * 组合xml内容 
     * @param string $msgtype text文字,news图文,music音乐
     * @param string $content 文字消息体
     * @param string $title 图文标题
     * @param string $description 图文简介
     * @param string $picurl 图文封面
     * @param string $url 图文链接
     * @param string $bodystr 已组合好的格式体，通常用在多图文中
     */
    public function create_xmlcontent($msgtype, $content='', $title='', $description='', $picurl='', $url='', $bodystr=''){
        if($msgtype == 'text'){
            $content = htmlspecialchars_decode($content);
            $bodystr = '<Content><![CDATA['.$content.']]></Content>';
        }elseif($msgtype == 'image'){
            $bodystr = "<Image>
                <MediaId><![CDATA['.$content.']]></MediaId>
                </Image>";
        }elseif($msgtype == 'music'){
            $bodystr = "<Music>
                <Title><![CDATA[$title]]></Title>
                <Description><![CDATA[$description]]></Description>
                <MusicUrl><![CDATA[$url]]></MusicUrl>
                <HQMusicUrl><![CDATA[$url]]></HQMusicUrl>
                </Music>";
        }
        
        $xmlcontent = "<xml>
            <ToUserName><![CDATA[".$this->post_data['FromUserName']."]]></ToUserName>
            <FromUserName><![CDATA[" . $this->post_data['ToUserName']."]]></FromUserName>
            <CreateTime>".time()."</CreateTime>
            <MsgType><![CDATA[".$msgtype."]]></MsgType>
            ".$bodystr."
            <FuncFlag>0</FuncFlag>
            </xml>";
        return $xmlcontent;
    }
    
    //公众平台校验
    private function valid($token){
        $echoStr   = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce     = $_GET["nonce"];

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr,SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature) return $echoStr;
    }
    
}
